package com.sto.stoapp.activity.aviation;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.StoLoginActivity;
import com.sto.stoapp.activity.administrator.system.AdminSystemSettingActivity;
import com.sto.stoapp.activity.sales.SalesTelphoneSmsActivity;
import com.sto.stoapp.activity.sales.SalesWdcpQueryActivity;
import com.sto.stoapp.activity.scanner.StoBusinessSetupActivity;
import com.sto.stoapp.activity.scanner.StoRecordscheckActivity;
import com.sto.stoapp.activity.scanner.StoUploadMainActivity;
import com.sto.stoapp.adapter.SoleMainAdapter;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.entity.FunctionEntity;
import com.sto.stoapp.http.MessageType;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.manager.AlarmClockManager;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.service.TimingService;
import com.sto.stoapp.upload.UploadDataService;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHomeActivity;

import java.util.ArrayList;
import java.util.List;

import sto.android.app.StoPdaKeyEvent;

public class StoAviationPickUpMainActivity extends StoHomeActivity {

	private GridView extractMainList;

	// 按键映射
	private static final int[] MAPP_TO_KEY = { R.string.logout,
			 R.string.inbound_scan,
			R.string.super_limits_search, R.string.record_search,
			R.string.record_upload, R.string.business_settings,
			 R.string.telphone_sms,
			R.string.system_settings };
	// R.string.down_cast,
	private SoleMainAdapter soleAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_aviation_pickup_main);
		this.setStoTitle(R.string.avi_pick_up_title);
		this.register(HomeBroadAction.PICKER_BROAD);
		initWidget();
//		UnSentDataManager.getInstance().setUnSent(
//				UploadDataManager.getInstance(this).getUnsendDataCount());
		initUnsentDataCount();
	}

	private void initWidget() {
		extractMainList = (GridView) findViewById(R.id.aviation_extract_main_list);
		soleAdapter = new SoleMainAdapter(this, getResourceList());
		extractMainList.setAdapter(soleAdapter);
		extractMainList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				arg1.setSelected(true);
				TextView title = (TextView) arg1.findViewById(R.id.res_test);
				clickItemEvent(title.getText().toString());
			}
		});
	}

	private void clickItemEvent(String title) {
		// 提货员-下载预报
		if (title.equals(getText(R.string.down_cast))) {
			downCast();
		}
		// 提货员-到包扫描
		else if (title.equals(getText(R.string.inbound_scan))) {
			checkTimeSyn(StoAviationsPacketScanActivity.class, this,
					HomeBroadAction.PICKER_BROAD);
		}
		// 提货员-无点超派
		else if (title.equals(getText(R.string.super_limits_search))) {
			Intent intent = new Intent(this, SalesWdcpQueryActivity.class);
			intent.putExtra("busiType", HomeBroadAction.PICKER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 提货员-记录查询
		else if (title.equals(getText(R.string.record_search))) {
			Intent intent = new Intent(this, StoRecordscheckActivity.class);
			intent.putExtra("busiType", HomeBroadAction.PICKER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 提货员-记录上传
		else if (title.equals(getText(R.string.record_upload))) {
			Intent intent = new Intent(this, StoUploadMainActivity.class);
			intent.putExtra("busiType", HomeBroadAction.PICKER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 提货员-业务设置
		else if (title.equals(getText(R.string.business_settings))) {
			Intent intent = new Intent(this, StoBusinessSetupActivity.class);
			intent.putExtra("busiType", HomeBroadAction.PICKER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}

		// 提货员-电话短信
		else if (title.equals(getText(R.string.telphone_sms))) {
			Intent intent = new Intent(this, SalesTelphoneSmsActivity.class);
			intent.putExtra("busiType", HomeBroadAction.PICKER_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 提货员-系统设置
		else if (title.equals(getText(R.string.system_settings))) {
			Intent intent = new Intent(this, AdminSystemSettingActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra(HomeBroadAction.BROAD_TYPE,
					HomeBroadAction.PICKER_BROAD);
			startActivity(intent);
		}
		// 用户切换
		else {
			onBackPressed();
		}
	}

	private void checkTimeSyn(final Class<?> c, final Context context,
			final String type) {
		if (!(StoFilePreference.getInstance(StoAviationPickUpMainActivity.this)
				.getsetTimeSynch())) {
			final BaseDialog dialog = new BaseDialog(this);
			dialog.setTitles(getString(R.string.synch_time_hint));
			dialog.show();
			dialog.setOnBackClickListener(new OnBackClickListener() {

				@Override
				public void onBackClickListener(boolean res) {
					dialog.dismiss();
					if (res) {
						Intent intent = new Intent(context, c);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intent.putExtra("busiType", type);
						startActivity(intent);
					}
				}
			});
		} else {
			Intent intent = new Intent(context, c);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("busiType", type);
			this.startActivity(intent);
		}
	}

	private List<FunctionEntity> getResourceList() {
		List<String> resList = new ArrayList<String>();
		int[] picIds = {  R.drawable.inbound_scan, // R.drawable.down_cast,
				R.drawable.super_limits_search, R.drawable.record_search,
				R.drawable.record_upload, R.drawable.business_settings,
				R.drawable.kai_after_sales, R.drawable.telphone_sms,
				R.drawable.system_settings, R.drawable.logout };
//		resList.add(getText(R.string.down_cast).toString());
		resList.add(getText(R.string.inbound_scan).toString());
		resList.add(getText(R.string.super_limits_search).toString());
		resList.add(getText(R.string.record_search).toString());
		resList.add(getText(R.string.record_upload).toString());
		resList.add(getText(R.string.business_settings).toString());
		resList.add(getText(R.string.telphone_sms).toString());
		resList.add(getText(R.string.system_settings).toString());
		resList.add(getText(R.string.logout).toString());

		List<FunctionEntity> functionList = new ArrayList<FunctionEntity>();
		for (int i = 0;i < resList.size();i++) {
			FunctionEntity entity = new FunctionEntity();
			entity.setTitle(resList.get(i));
			entity.setPicId(picIds[i]);
			functionList.add(entity);
		}
		return functionList;
	}

	/**
	 * 现在预报
	 */
	private void downCast() {
		final BaseDialog dialog = new BaseDialog(this);
		dialog.setTitles(getString(R.string.down_cast_notice));
		dialog.show();
		dialog.getvMessage().setVisibility(View.GONE);
		dialog.getvPresentation().setVisibility(View.GONE);
		dialog.setOnBackClickListener(new OnBackClickListener() {

			@Override
			public void onBackClickListener(boolean res) {
				if (res) {
					Intent downIntent = new Intent(StoDownServer.UPDATE_ACTION);
					downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS,
							new int[] { MessageType.DOWN_CAST_TYPE });
					sendBroadcast(downIntent);
					Helper.showToast(StoAviationPickUpMainActivity.this,
							getString(R.string.down_fore_cast));
				}
				dialog.dismiss();
			}
		});

	}

	/**
	 * 退回到登入界面
	 */
	@Override
	public void onBackPressed() {
		// new AlertDialog.Builder(this)
		// .setTitle(R.string.prompt)
		// .setMessage(R.string.change_user)
		// .setPositiveButton(R.string.change,
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog,
		// int which) {
		// // 恢复时间同步和订单状态
		// Intent intent = new Intent(
		// StoAviationPickUpMainActivity.this,
		// StoLoginActivity.class);
		// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// startActivity(intent);
		// stopStoService();
		// finish();
		// }
		// })
		// .setNegativeButton(R.string.cancel,
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog,
		// int which) {
		// dialog.dismiss();
		// }
		// }).setCancelable(false).show();
		final BaseDialog dialog = new BaseDialog(this);
		dialog.setTitles(this.getText(R.string.change_user).toString());
		dialog.show();
		dialog.getvMessage().setVisibility(View.GONE);
		dialog.getvPresentation().setVisibility(View.GONE);
		dialog.setOnBackClickListener(new OnBackClickListener() {

			@Override
			public void onBackClickListener(boolean res) {
				dialog.dismiss();
				if (res) {
					// 恢复时间同步和订单状态
					Intent intent = new Intent(
							StoAviationPickUpMainActivity.this,
							StoLoginActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					stopStoService();
				//	new LogoutThread(StoAviationPickUpMainActivity.this, null, false).start();
					finish();
				}
				

			}
		});

	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		// 退出
		if (intent.getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE) != null) {
			if ((Intent.FLAG_ACTIVITY_CLEAR_TOP & intent.getFlags()) != 0
					&& intent
							.getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE)
							.equals(HomeBroadAction.ALARM_LOGOUT)) {
				Intent logoutIntent = new Intent(this, StoLoginActivity.class);
				startActivity(logoutIntent);
				stopStoService();
				finish();
			}
		}
	}

//	/**
//	 * 按键映射 数字键映功能，0代表列表第10项
//	 */
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (keyCode >= KeyEvent.KEYCODE_0 && keyCode < KeyEvent.KEYCODE_9) {
//			clickItemEvent(getString(MAPP_TO_KEY[keyCode - KeyEvent.KEYCODE_0]));
//		}
//		return super.onKeyDown(keyCode, event);
//	}

	/**
	 * 小退 返回航空选择界面
	 */
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		keyCode=StoApplication.getStoJni().getEventFuction(keyCode);
		if (keyCode == StoPdaKeyEvent.KEYCODE_DEL) {
			startActivity(new Intent(this, StoAviationSelectActivity.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
			this.finish();
		}
		return super.onKeyUp(keyCode, event);
	}

	/**
	 * 切换用户时 停止后台服务
	 */
	private void stopStoService() {
		// 退出的时候关闭后台服务
		StoFilePreference.getInstance(this).clearTimeSynData();
		stopService(new Intent(this, StoDownServer.class));
		stopService(new Intent(this, UploadDataService.class));
		stopService(new Intent(this, TimingService.class));
	}

	@Override
	protected void onDestroy() {
		// stopStoService();
		super.onDestroy();
	}
}
